/**
 * @author YinHang
 */
;(function () {
	var Controller = Gamepackage.get("Gamepackage.ui.Controller");
	
	Controller.TARGET;
	Controller.STATES = 0;
	Controller.UNIQUE_CODE = 1;
	Controller.KEYS = {};
	Controller.MOUSE_EVENT_STACK = [];
	Controller.MOUSE_EVENT_BUFFER = {};
	
	Controller.addKey = function (keyCode) {
		if(!Controller.KEYS)
			Controller.KEYS = {};
		Controller.KEYS[keyCode] = Controller.UNIQUE_CODE;
		Controller.UNIQUE_CODE <<= 1;
	};
	
	Controller.pushMouseEvent = function (event) {
		event.viewX = event.clientX - Controller.TARGET.offsetLeft;
		event.viewY = event.clientY - Controller.TARGET.offsetTop;
		Controller.MOUSE_EVENT_BUFFER[event.type] = event;
	};
	
	Controller.popMouseEvent = function (type) {
		var event = Controller.MOUSE_EVENT_BUFFER[type];
		delete Controller.MOUSE_EVENT_BUFFER[type];
		return event;
	};
	
	Controller.cleanAllMouseEvent = function () {
		Controller.MOUSE_EVENT_BUFFER = [];
	};
	
	Controller.addKeyList = function (list) {
		var listLength = list.length;
		for(var i=0;i<listLength;++i)
			Controller.addKey(list[i]);
	};
	
	Controller.cleanKeys = function () {
		Controller.KEYS = {};
		Controller.UNIQUE_CODE = 1;
		Controller.STATES = 0;
	};
	
	Controller.removeTarget = function () {
		if(Controller.TARGET)
		{
			delete Controller.TARGET.onmouseup;
			delete Controller.TARGET.onmousedown;
			delete document.onkeyup;
			delete document.onkeydown;
		}
	};
	
	Controller.setTarget = function (target) {
		Controller.removeTarget();
		Controller.TARGET = target;
		Controller.TARGET.onmouseup = function (e) {
			if(e.target == Controller.TARGET)
			{
				Controller.pushMouseEvent(e);
			}
		};
		Controller.TARGET.onmousedown = function (e) {
			if(e.target == Controller.TARGET)
			{
				Controller.pushMouseEvent(e);
			}
		};
		Controller.TARGET.ondbclick = function (e) {
			if(e.target == Controller.TARGET)
			{
				Controller.pushMouseEvent(e);
			}
		};
		Controller.TARGET.onclick = function (e) {
			if(e.target == Controller.TARGET)
			{
				Controller.pushMouseEvent(e);
			}
		};
		Controller.TARGET.onmousemove = function (e) {
			if(e.target == Controller.TARGET)
			{
				Controller.pushMouseEvent(e);
			}
		};
		document.onkeyup = function (e) {
			if(Controller.KEYS[e.keyCode])
				Controller.STATES ^= Controller.KEYS[e.keyCode];
		};
		document.onkeydown = function (e) {
			if(Controller.KEYS[e.keyCode])
				Controller.STATES |= Controller.KEYS[e.keyCode];
		};
	};
	
	Controller.getKeyStates = function () {
		return Controller.STATES;
	};
	
	Controller.getState = function (code) {
		if(Controller.KEYS[code])
			return Controller.getKeyStates() & Controller.KEYS[code];
	};
})();
